import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * Created by hasee on 2017/8/22.
 */
public class Yard extends Frame{
    static final int CROSS_LINE = 30;//横线数
    static final int VERTICAL_LINE = 30;//竖线数
    public static final int BLOCK_SIZE = 20;//方格边长

    Yard yard;
    Snake snake = new Snake(yard,5,5, Dir.R);
    Food food = new Food();

    public void ganmeStart(){
        yard = new Yard();
        yard.setTitle("贪吃蛇");
        yard.setBackground(Color.gray);
        yard.setBounds(500,300,600,600);
        yard.setLayout(null);
        yard.setResizable(false);//用户不可改变窗口大小
        yard.setVisible(true);//窗口可见
        yard.addWindowListener(new WindowAdapter() {//按X关闭程序
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });//添加窗口监听器

        yard.addKeyListener(new KeyMonitor());//添加键盘监听器
    }

    public void paint(Graphics g){
        snake.move();//如果蛇是活的，蛇就调用move方法，蛇的位置发生变化，Frame中画面发生变化，Frame再次调用paint方法
        Color c = g.getColor();
        g.setColor(Color.black);
        for (int i = 1; i < VERTICAL_LINE; i++) {
            g.drawLine(0,i*BLOCK_SIZE,VERTICAL_LINE*BLOCK_SIZE,i*BLOCK_SIZE);
        }
        for (int i = 1; i < CROSS_LINE; i++) {
            g.drawLine(i*BLOCK_SIZE,0,i*BLOCK_SIZE,CROSS_LINE*BLOCK_SIZE);
        }
        g.setColor(c);
        snake.draw(g);
        food.makeFood();
        food.refreshFood(snake.iterator());
        food.draw(g);
        repaint();//刷新画面
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void ganmeKey(KeyEvent e){
        if(snake.isKeyLive==false){return;}
        switch (e.getKeyCode()){
            case KeyEvent.VK_S:
                if (Snake.isAlive==true){
                    Snake.isAlive=false;
                    System.out.println("游戏暂停");
                    return;}
                    Snake.isAlive=true;
                    System.out.println("游戏开始");
                    break;//暂停游戏。原理:把蛇isAlive设为false,来阻止蛇调用move()方法
        }
    }

   public class KeyMonitor extends KeyAdapter{//键盘监听器
       @Override
       public void keyPressed(KeyEvent e) {
           snake.changeDir(e);
           yard.ganmeKey(e);
       }
   }

    public static class MyRunnable implements Runnable {//该游戏线程
        @Override
        public void run() {
            Yard yard = new Yard();
            yard.ganmeStart();
        }
    }
}
